package com.zzyl.framework.interceptor.impl;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        strictInsertFill(metaObject,"createBy", String.class,String.valueOf(loadUserId()));
        strictInsertFill(metaObject,"createTime",Date.class,new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
//        strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
//        strictUpdateFill(metaObject, "updateBy", String.class, String.valueOf(loadUserId()));
        //新的自动更新策略
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", String.valueOf(loadUserId()), metaObject);
    }
    //获取登录人的ID
    public Long loadUserId(){
        LoginUser loginUser= SecurityUtils.getLoginUser();
        if(loginUser !=null){
            return loginUser.getUserId();
        }
        return 1L;
    }

}
